package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.web.AjaxResult;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipInputStream;


@Service
public class BpmnInfoServiceImpl implements IBpmnInfoService {
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public Long saveBpmnInfo(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //文件名
        String extName = FilenameUtils.getExtension(originalFilename); //扩展名
        Deployment deploy = null;
        if("bpmn".equalsIgnoreCase(extName)){
            deploy = repositoryService.createDeployment()
                    .addInputStream(originalFilename, file.getInputStream())
                    .deploy();
        }else{
            deploy = repositoryService.createDeployment()
                    .addZipInputStream(new ZipInputStream(file.getInputStream()))
                    .deploy();
        }

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();


        bpmnInfoMapper.deleteByProcessKey(processDefinition.getKey());

        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());
        bpmnInfoMapper.insert(bpmnInfo);

        return bpmnInfo.getId();
    }

    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        bpmnInfoMapper.deleteByPrimaryKey(id);

        // TODO: 2024/5/30 修改已发起审批的状态
        List<ProcessInstance> instances = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(bpmnInfo.getActProcessKey())
                .list();
        for (ProcessInstance instance : instances) {
            String businessKey = instance.getBusinessKey();
            Long carPackageAuditId = Long.valueOf(businessKey);
            CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(carPackageAuditId);
            carPackageAuditMapper.changeAuditStatus(audit.getId(), CarPackageAudit.STATUS_CANCEL);
            serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        }


        List<Deployment> list = repositoryService.createDeploymentQuery()
                .processDefinitionKey(bpmnInfo.getActProcessKey())
                .list();
        for (Deployment deployment : list) {
            //参数2设置为true表示在删除流程定义时级联删除该流程定义发起的所有流程实例
            repositoryService.deleteDeployment(deployment.getId(), true);
        }

    }

    @Override
    public InputStream getResourceByType(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        if("xml".equalsIgnoreCase(type)){
            InputStream inputStream = repositoryService.getResourceAsStream(deploymentId, definition.getResourceName());
            return inputStream;
        }else if("png".equalsIgnoreCase(type)){
            //bpmnModel中存户了bpmn相关的信息，可以用于png图片的绘制
            BpmnModel bpmnModel = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            InputStream inputStream = generator.generateDiagram(bpmnModel
                    , Collections.emptyList()   //高亮的Activiti
                    , Collections.emptyList()   //高亮的箭头
                    , "宋体"      //activiti字体
                    , "宋体"       //label字体
                    , "宋体");//注解字体
            return inputStream;
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String type) {
        return bpmnInfoMapper.selectByType(type);
    }


}
